
package com.mengmeizi.services;

import com.mengmeizi.R;
import com.mengmeizi.util.Const;
import com.mengmeizi.util.DownloadManager;
import com.mengmeizi.util.Tools;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;

public class UpgradeService extends Service implements Callback {

    private NotificationManager mNotificationManager;

    private String downUrl;

    private Notification mNotification;

    private DownloadManager manager;

    private Handler handler;

    private NetWorkReceiver netReciver;

    private boolean isStop;

    private String downloadFileName;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        mNotificationManager = (NotificationManager) getSystemService(android.content.Context.NOTIFICATION_SERVICE);
        handler = new Handler(this);
    }

    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);
        try {
            if (getNetworkInfo(this)) {
                if (intent != null) {
                    downUrl = intent.getStringExtra("downUrl");
                    // 初始化通知栏界面
                    setUpNotification();
                    // 在下载管理器进行文件下载
                    downloadFileName = Tools.getSDCardPath() + "/" + getPackageName() + ".apk";
                    manager = new DownloadManager(this, downUrl, downloadFileName);
                    // 更新下载界面
                    new Thread() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            super.run();
                            downloadUpdate();
                        }

                    }.start();
                    // 注册监控网络的broadcast
                    netReciver = new NetWorkReceiver();
                    registerReceiver(netReciver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            mNotificationManager.cancel(Const.NOTIFY_ID);
        }
    }

    /***
     * 更新下载界面
     */
    private void downloadUpdate() {
        int rate = 0;
        while (!isStop && rate < 100) {
            try {
                // 每隔500毫秒更新一次下载进度条
                Thread.sleep(500);
                rate = manager.getDownRate();
                // 发送更新信息
                Message msg = handler.obtainMessage();
                msg.what = 1;
                msg.arg1 = rate;
                handler.sendMessage(msg);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if (isStop) {
            Message msg = handler.obtainMessage();
            msg.what = 0;
            handler.sendMessage(msg);
        }
    }

    /**
     * 创建通知
     */
    private void setUpNotification() {
        int icon = android.R.drawable.stat_sys_download;
        CharSequence tickerText = "正在下载";
        long when = System.currentTimeMillis();
        mNotification = new Notification(icon, tickerText, when);
        // 放置在"正在运行"栏目中
        mNotification.flags = Notification.FLAG_ONGOING_EVENT;

        RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.download_remoteview);
        contentView.setTextViewText(R.id.txvAppName, getString(R.string.app_name));
        // 指定个性化视图
        mNotification.contentView = contentView;
        mNotification.contentView.setImageViewResource(R.id.imvIcon, R.drawable.icon);

        mNotificationManager.notify(Const.NOTIFY_ID, mNotification);
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case 1:
                int rate = msg.arg1;
                if (rate < 100) {
                    // 更新进度
                    RemoteViews contentView = mNotification.contentView;
                    contentView.setTextViewText(R.id.txvDownloadRate, "下载中: " + rate + "%");
                    contentView.setInt(R.id.pgbDownload, "setProgress", rate);
                } else {
                    // 下载完毕后变换通知形式
                    mNotification.flags = Notification.FLAG_AUTO_CANCEL;
                    mNotification.contentView = null;
                    // 提示安装
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setDataAndType(Uri.parse("file://" + downloadFileName),
                            "application/vnd.android.package-archive");
                    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent,
                            PendingIntent.FLAG_UPDATE_CURRENT);
                    mNotification.setLatestEventInfo(this, "软件下载完成", "请点击安装", contentIntent);
                    stopSelf();// 停掉服务自身
                }
                mNotificationManager.notify(Const.NOTIFY_ID, mNotification);
                break;
            case 0:
                mNotificationManager.cancel(Const.NOTIFY_ID);
                manager.setStatus(false);
                stopSelf();
                break;
            default:
                break;
        }

        return false;
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        // 注销网络监听
        if (netReciver != null) {
            unregisterReceiver(netReciver);
        }
    }

    class NetWorkReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                if (!getNetworkInfo(context)) {
                    isStop = true;
                }
            }
        }
    }

    /***
     * 获取当前网络状态
     * 
     * @param context
     * @return
     */
    private boolean getNetworkInfo(Context context) {
        boolean networkState = false;
        ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connManager.getActiveNetworkInfo();
        if (info != null && info.isAvailable()) {
            networkState = true;
        }
        return networkState;
    }

}
